/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * listCargo.java
 *
 * Created on 25/11/2011, 16:12:21
 */
package visao;

import cargo.Cargo;
import fachada.FachadaBDR;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import util.CamposObrigatoriosException;
import util.ErroAcessoRepositorioException;

/**
 *
 * @author amedeiros
 */
public class listCargo extends javax.swing.JFrame {

    public String[] titulos = new String[]{"#", "Descrição Cargo", "Status"};
    public DefaultTableModel defTable;
    public CadCargo cadastroCargo = new CadCargo();

    /** Creates new form listCargo */
    public listCargo() {
        try {

            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

            List<Cargo> listCargo = objFachadaBDR.listarCargo(" AND status_cargo = true order by id_cargo");

            // Setando a tabela
            this.defTable = atualizaLista(listCargo);

        } catch (CamposObrigatoriosException ex) {
            System.out.println(ex.getMessage());
        } catch (ErroAcessoRepositorioException ex) {
            System.out.println(ex.getMessage());
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

        initComponents();
        this.setLocationRelativeTo(null);
        this.setIconImage(new ImageIcon(getClass().getResource("/Imagens/Cargo.gif")).getImage());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton_Cadastrar = new javax.swing.JButton();
        jButton_Editar = new javax.swing.JButton();
        jButton_Atualizar = new javax.swing.JButton();
        jButton_Remover = new javax.swing.JButton();
        jTextField_Buscar = new javax.swing.JTextField();
        jButton_Buscar = new javax.swing.JButton();
        jLabel_Buscar = new javax.swing.JLabel();
        jLabel_Mensagem = new javax.swing.JLabel();

        setTitle("Cargo");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jTable1.setModel(this.defTable);
        jScrollPane1.setViewportView(jTable1);

        jButton_Cadastrar.setText("Cadastrar");
        jButton_Cadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_CadastrarActionPerformed(evt);
            }
        });

        jButton_Editar.setText("Editar");
        jButton_Editar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_EditarActionPerformed(evt);
            }
        });

        jButton_Atualizar.setText("Atualizar");
        jButton_Atualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_AtualizarActionPerformed(evt);
            }
        });

        jButton_Remover.setText("Remover");
        jButton_Remover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_RemoverActionPerformed(evt);
            }
        });

        jTextField_Buscar.setText("");
        jTextField_Buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField_BuscarActionPerformed(evt);
            }
        });

        jButton_Buscar.setText("Buscar");
        jButton_Buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_BuscarActionPerformed(evt);
            }
        });

        jLabel_Buscar.setText("Descrição Cargo");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel_Mensagem, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 663, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel_Buscar)
                            .addGap(18, 18, 18)
                            .addComponent(jTextField_Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(jButton_Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jButton_Cadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(jButton_Editar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(jButton_Atualizar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(jButton_Remover, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 663, Short.MAX_VALUE)))
                .addContainerGap(21, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_Buscar)
                    .addComponent(jTextField_Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel_Buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 340, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_Cadastrar)
                    .addComponent(jButton_Editar)
                    .addComponent(jButton_Atualizar)
                    .addComponent(jButton_Remover))
                .addGap(29, 29, 29)
                .addComponent(jLabel_Mensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(16, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jTextField_BuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_BuscarActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField_BuscarActionPerformed

private void jButton_CadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CadastrarActionPerformed
    try {
        if (!this.cadastroCargo.isVisible()) {
            this.cadastroCargo = new CadCargo();
            this.cadastroCargo.setVisible(true);
        }

        FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
        List<Cargo> listCargo = objFachadaBDR.listarCargo(" AND status_cargo = true ");

        // Setando a tabela
        this.defTable = atualizaLista(listCargo);

        // Setando a nova listagem
        jTable1.setModel(this.defTable);

        jTable1.revalidate();

    } catch (Exception ex) {
        jLabel_Mensagem.setText(ex.getMessage());
    }
}//GEN-LAST:event_jButton_CadastrarActionPerformed

private void jButton_EditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_EditarActionPerformed

    try {
        // pegando a linha selecionada
        if (this.jTable1.getSelectedColumnCount() == 0) {
            throw new Exception("Favor selecionar um Cargo");
        }

        // Pegando a linha que está selecionada
        int linha = this.jTable1.getSelectedRow();
        // recuperando o Cpf do funcionario
        int idCargo = (Integer) this.jTable1.getValueAt(linha, 0);

        FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

        Cargo objCargo = objFachadaBDR.procurarCargo(idCargo);

        // se a tela de cargo ja estiver instanciada
        if (!this.cadastroCargo.isVisible()) {
            this.cadastroCargo = new CadCargo(objCargo.getIdCargo());
            this.cadastroCargo.setVisible(true);
        }
        // Listando os cargos
        List<Cargo> listCargo = objFachadaBDR.listarCargo(" AND status_cargo = true ");

        // Setando a tabela
        this.defTable = atualizaLista(listCargo);

        // Setando a nova listagem
        jTable1.setModel(this.defTable);

        // atualizando os cargos
        jTable1.revalidate();
        jLabel_Mensagem.setText("");
    } catch (Exception ex) {
        jLabel_Mensagem.setText(ex.getMessage());
    }
}//GEN-LAST:event_jButton_EditarActionPerformed

private void jButton_AtualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_AtualizarActionPerformed
    // TODO add your handling code here:
    try {
        // instanciando a fachada
        FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

        // Listando os cargos
        List<Cargo> listCargo = objFachadaBDR.listarCargo(" AND status_cargo = true ");

        // Setando a tabela
        this.defTable = atualizaLista(listCargo);

        // Setando a nova listagem
        jTable1.setModel(this.defTable);

        jTable1.revalidate();
    } catch (Exception ex) {
        jLabel_Mensagem.setText(ex.getMessage());
    }
}//GEN-LAST:event_jButton_AtualizarActionPerformed

private void jButton_RemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_RemoverActionPerformed
    // TODO add your handling code here:
    int cancelar = JOptionPane.showConfirmDialog(null, "Deseja Remover este Cargo?");
    if (cancelar == JOptionPane.YES_OPTION) {
        try {
            // pegando a linha selecionada
            if (this.jTable1.getSelectedColumnCount() == 0 || this.jTable1.getSelectedColumnCount() > 1) {
                throw new Exception("Favor selecionar um Cargo");
            }

            int linha = this.jTable1.getSelectedRow();

            // recuperando o Cpf do funcionario
            int idCargo = (Integer) this.jTable1.getValueAt(linha, 0);

            // instanciando a fachada
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

            // Listando os cargos
            objFachadaBDR.removerCargo(idCargo);

            // Listando os cargos
            List<Cargo> listCargo = objFachadaBDR.listarCargo(" AND status_cargo = true ");

            // Setando a tabela
            this.defTable = atualizaLista(listCargo);

            // Setando a nova listagem
            jTable1.setModel(this.defTable);

            jTable1.revalidate();

            jLabel_Mensagem.setText("Removido com sucesso!");

        } catch (Exception ex) {
            jLabel_Mensagem.setText(ex.getMessage());
        }
    }
}//GEN-LAST:event_jButton_RemoverActionPerformed

private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
// TODO add your handling code here:
}//GEN-LAST:event_formWindowClosed

private void jButton_BuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_BuscarActionPerformed
    // TODO add your handling code here:
    try {
        // instanciando a fachada
        FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

        String descricaoCargo = jTextField_Buscar.getText();
        // Listando os cargos
        List<Cargo> listCargo = objFachadaBDR.procurarCargoPorDescricao(descricaoCargo);

        // Setando a tabela
        this.defTable = atualizaLista(listCargo);

        // Setando a nova listagem
        jTable1.setModel(this.defTable);
        jTable1.revalidate();
    } catch (Exception ex) {
        jLabel_Mensagem.setText(ex.getMessage());
    }
}//GEN-LAST:event_jButton_BuscarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(listCargo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(listCargo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(listCargo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(listCargo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    new listCargo().setVisible(true);
                } catch (Exception ex) {
                    Logger.getLogger(listCargo.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    public DefaultTableModel atualizaLista(List<Cargo> listCargo) {
        // Criando o objeto 
        Object[][] resposta = new Object[listCargo.size()][4];

        for (int i = 0; i < resposta.length; i++) {
            Cargo objCargo = listCargo.get(i);
            resposta[i][0] = objCargo.getIdCargo();
            resposta[i][1] = objCargo.getDescricaoCargo();
            resposta[i][2] = (objCargo.getStatusCargo()) ? "Ativo" : "Inativo";
        }

        // Setando a tabela
        return new DefaultTableModel(resposta, titulos);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_Atualizar;
    private javax.swing.JButton jButton_Buscar;
    private javax.swing.JButton jButton_Cadastrar;
    private javax.swing.JButton jButton_Editar;
    private javax.swing.JButton jButton_Remover;
    private javax.swing.JLabel jLabel_Buscar;
    private javax.swing.JLabel jLabel_Mensagem;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField_Buscar;
    // End of variables declaration//GEN-END:variables
}
